<template>
  <div class="login">
    <el-form
      ref="form"
      :model="form"
      label-position="top"
      label-width="80px"
      :rules="rules"
    >
      <header class="header">后台管理系统</header>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login-btn"
          type="primary"
          @click="onSubmit"
          :loading="isSubmitting"
        >登录</el-button
      >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Form } from 'element-ui'
import { login } from '@/apis/user'

export default Vue.extend({
  name: 'login',
  data() {
    return {
      form: {
        phone: '18201288771',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      },
      isSubmitting: false
    }
  },
  methods: {
    async onSubmit() {
      try {
        // 提交状态更改，防止网络缓慢，多次点击提交
        this.isSubmitting = true
        // 前端验证
        await (this.$refs.form as Form).validate()

        const { data } = await login(this.form)
        if (data.state === 1) {
          this.$message.success('登录成功')
          this.$store.commit('setUser', data.content)
          this.$router.push({ path: this.$route.query.rediret as string || '/' })
        } else {
          this.$message.error('登录失败')
        }
      } catch (error) {
        console.log('登录失败', error)
      }
      this.isSubmitting = false
    }
  }
})
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .el-form {
    width: 400px;
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    .header {
      width: 100%;
      text-align: center;
      font-size: 28px;
      margin-bottom: 30px;
    }
  }
  .login-btn {
    width: 100%;
  }
}
</style>
